package com.mallbook.model.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * @Author 宋明松
 * @Version V1.0.0
 * @Date 2022-06-23
 * Mybatis工具类,返回对应类的mapper
 */
public class MybatisUtils {
    private static SqlSessionFactory sqlSessionFactory;
    private static ThreadLocal<SqlSession> sessions = new ThreadLocal<>();

    static {
        InputStream inputStream = null;
        try {
            inputStream = Resources.getResourceAsStream("mybatis-config.xml");
        } catch (IOException e) {
            e.printStackTrace();
        }
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    }

    public static SqlSession getSession() {
        SqlSession session = sessions.get();
        if (session == null) {
            session = sqlSessionFactory.openSession();
        }
        return session;
    }

    public static <T> T getMappers(Class<T> c) {
        return getSession().getMapper(c);
    }

}
